package com.hmdp.Interceptors;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.LoginConstant.LOGIN_USER;
import static com.hmdp.constants.TimeConstant.LOGIN_USER_TIME;

/**
 * @author HUAWEI
 * 登录拦截器
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、从请求头中取出token，从Redis中获取用户
        String token = request.getHeader("authorization");
        if (token == null) {
            return true;
        }
        String key = LOGIN_USER + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        UserDTO user = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        // 2、判断用户是否存在
        if (user == null) {
            return true;
        }
        // 2.2、存在，将用户保存在ThreadLocal中
        UserHolder.saveUser(user);
        // 3、刷新用户的登录态
        stringRedisTemplate.expire(key, LOGIN_USER_TIME, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 移除用户的登录状态
        UserHolder.removeUser();
    }
}
